﻿using MySqlX.XDevAPI.Relational;
using Newtonsoft.Json;
using QskjFileWatermark.Dto;
using QskjLibrary;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;

namespace QskjFileWatermark.Service
{
    public static class FileAddWatermark
    {
        public static void GetFileUrl()
        {
            try
            {
                List<FileWatermarkDto> list = new List<FileWatermarkDto>();
                string sql = $@"select * from qskj.B_WatermarkFile where filestatus ='0'";
                DataTable dt = MySqlHelper.GetDataTable(CommandType.Text, sql);
                foreach (DataRow dr in dt.Rows)
                {
                    FileWatermarkDto dto = new FileWatermarkDto();
                    dto.fileurl = dr["fileurl"] == DBNull.Value ? "" : dr["fileurl"].ToString();
                    dto.filestatus = dr["filestatus"] == DBNull.Value ? "" : dr["filestatus"].ToString();
                    dto.filewatermarkinfo = dr["filewatermarkinfo"] == DBNull.Value ? "" : dr["filewatermarkinfo"].ToString();
                    dto.filewatermarkurl = dr["filewatermarkurl"] == DBNull.Value ? "" : dr["filewatermarkurl"].ToString();
                    dto.starttime = dr["starttime"] == DBNull.Value ? "" : dr["starttime"].ToString();
                    dto.filekey = dr["filekey"] == DBNull.Value ? "" : dr["filekey"].ToString();
                    dto.createuser = dr["createuser"] == DBNull.Value ? "" : dr["createuser"].ToString();
                    dto.fontsize = dr["fontsize"] == DBNull.Value ? "" : dr["fontsize"].ToString();
                    dto.transparency = dr["transparency"] == DBNull.Value ? "" : dr["transparency"].ToString();
                    list.Add(dto);
                }
                foreach (var item in list)
                {
                    DownLoadFile(item);
                }
            }
            catch (Exception e)
            {

                throw;
            }
        }
        /// <summary>
        /// 下载文件并添加水印
        /// </summary>
        /// <param name="item"></param>
        private static void DownLoadFile(FileWatermarkDto item)
        {
            try
            {
                string videourl = item.fileurl;
                string[] filetype = videourl.Split('.');
                string[] filename = videourl.Split('/');
                string filetype1 = filetype[(filetype.Length - 1)];
                string filename1 = filename[(filename.Length - 1)];
                string bt = DateTime.Now.ToString("yyyyMMddHHmmss"), urladdress = string.Empty;
                string strKey = bt + DateTime.Now.Ticks, fileName = "videoFile_" + filename1, fileWaterName = "videoFileWatermark_" + filename1;
                string localFilePath = AppDomain.CurrentDomain.BaseDirectory + fileName, watermarkFilePath = AppDomain.CurrentDomain.BaseDirectory + fileWaterName;
                // 创建目标文件夹（如果不存在）
                Directory.CreateDirectory(Path.GetDirectoryName(localFilePath));
                if (!File.Exists(localFilePath))
                {
                    // 下载文件并保存到本地
                    using (WebClient client = new WebClient())
                    {
                        client.DownloadFile(videourl, localFilePath);
                    }
                    {
                        //查询水印信息
                        if (string.IsNullOrWhiteSpace(item?.filewatermarkinfo))
                        {
                            string fw = $@"select CONCAT(watermarktext, ',',fontsize,',',transparency,',',rotation,',',isused)a from qskj.B_WatermarkUserInfo where username='{item.createuser}' order by id desc limit 1;";
                            object rfw = MySqlHelper.ExecuteScalar(CommandType.Text, fw);
                            if (rfw != null)
                            {
                                item.filewatermarkinfo = rfw.ToString();
                            }
                        }
                        //查不到水印信息，默认给当前用户名
                        if (string.IsNullOrWhiteSpace(item?.filewatermarkinfo))
                        {
                            item.filewatermarkinfo = item.createuser;
                        }
                        AddTextWatermark(localFilePath, watermarkFilePath, item.filewatermarkinfo, item.fontsize, item.transparency);
                    }
                    if (filetype1 == "mp4")
                    {
                        try
                        {
                            //string? videourl = "https://rvming.zx62580.com:48086/videoAlarm/2024/06/17/沪AC15032/02_03_0_0_253418146.mp4";
                            #region 上传文件信息
                            var dataInfoRes = PostFileDataInfo(strKey, "mp4", fileWaterName, bt); Thread.Sleep(10);
                            DataInfo responseDataInfo = new DataInfo();
                            responseDataInfo = JsonConvert.DeserializeObject<DataInfo>(dataInfoRes.Result);
                            #endregion
                            #region 上传文件 
                            {
                                try
                                {
                                    var dataRes = PostFileData(strKey, watermarkFilePath);
                                    DataFile responseData = new DataFile();
                                    responseData = JsonConvert.DeserializeObject<DataFile>(dataRes.Result);
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("上传文件异常" + e.ToString());
                                }
                            }
                            #endregion
                            #region 查询文件信息
                            urladdress = GetUrl(strKey, "mp4", bt);
                            #endregion
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("上传文件信息异常" + e.ToString());
                        }
                    }
                    #region 更新信息
                    {
                        //删除本地资源文件
                        File.Delete(localFilePath); File.Delete(watermarkFilePath);
                        string sql = $@"update qskj.B_WatermarkFile set filewatermarkurl='{urladdress}',filestatus='1',starttime='{bt}',filekey='{strKey}' where fileurl='{item.fileurl}';";
                        MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sql);
                    }
                    #endregion
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        #region 视图库相关
        /// <summary>
        /// 上传视图库数据结构
        /// </summary> 
        /// <param name="key">Id</param>
        /// <param name="s">格式</param>
        /// <param name="n">文件名</param>
        /// <returns></returns>
        private static async Task<string> PostFileDataInfo(string key, string s, string n, string bt)
        {
            var client = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Post, "http://192.168.3.223:8000/VIID/VideoSlices");
            var content = new StringContent("{\r\n    \"VideoSliceListObject\": {\r\n        \"VideoSlice\": [\r\n            {\r\n                \"VideoSliceInfo\": {\r\n                    \"VideoID\": \"" + key + "\",\r\n                    \"InfoKind\": 0,\r\n                    \"VideoSource\": \"\",\r\n                    \"FileFormat\": \"" + s + "\",\r\n                    \"CodedFormat\": \"\",\r\n                    \"AudioFlag\": 0,\r\n                    \"Title\": \"" + n + "\",\r\n                    \"ContentDescription\": \"\",\r\n                    \"ShotPlaceCode\": \"\",\r\n                    \"VideoLen\": 0.0,\r\n                    \"BeginTime\": \"" + bt + "\",\r\n                    \"EndTime\": \"\",\r\n                    \"TimeErr\": 0,\r\n                    \"Width\": 0,\r\n                    \"Height\": 0\r\n                }\r\n            }\r\n        ]\r\n    }\r\n}", null, "application/json");
            request.Content = content;
            var response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            string res = await response.Content.ReadAsStringAsync();
            return res;
        }
        /// <summary>
        /// 上传视图库视频文件
        /// </summary>
        /// <returns></returns>
        private static async Task<string> PostFileData(string key, string filePath = null)
        {
            using (FileStream file = File.OpenRead(filePath))
            {
                var client = new HttpClient();
                var request = new HttpRequestMessage(HttpMethod.Post, "http://192.168.3.223:8000/VIID/FileData/" + key + "/VideoSlices");
                //request.Content = (content);
                //content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                request.Content = new StreamContent(file);
                request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                var response = await client.SendAsync(request);
                response.EnsureSuccessStatusCode();
                string res = await response.Content.ReadAsStringAsync();
                return res;
            }
        }
        /// <summary>
        /// 视图库视频文件查询
        /// </summary>
        /// <returns></returns>
        public static async Task<string> GetFileDataUrl(string key, string dts, string dte, string begintime)
        {
            var client = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Get, $@"http://192.168.3.223:8000/VIID/VideoSlices?VideoID={key}&BeginTime={begintime}");
            var response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            string res = await response.Content.ReadAsStringAsync();
            return res;
        }
        #endregion
        #region 添加水印处理
        public static void AddTextWatermark(string inFile, string outputVideoPath, string watermarkText, string? fontsize = null, string? transparency = null)
        {
            try
            {
                string wm = $@"{watermarkText}_{DateTime.Now.ToString("yyyyMMddHHmmss")}_{watermarkText}_{DateTime.Now.ToString("yyyyMMddHHmmss")}";//水印文本信息
                string arguments = $"-i " + inFile + " -filter_complex \"color=White:s=1200x700[v1];[v1]drawtext=fontfile=" + AppDomain.CurrentDomain.BaseDirectory + "SIMSUN.TTC:text='" + wm + "':x=" + 0 + ":y=" + 90 + ":fontsize=40,drawtext=fontfile=" + AppDomain.CurrentDomain.BaseDirectory + "SIMSUN.TTC:text='" + wm + "':x=" + 150 + ":y=" + 360 + ":fontsize=40,drawtext=fontfile=" + AppDomain.CurrentDomain.BaseDirectory + "SIMSUN.TTC:text='" + wm + "':x=" + 300 + ":y=" + 600 + ":fontsize=40[o1];[o1]rotate=a=-PI*30/180:fillcolor=White@0[o1];[o1]colorkey=White:0.01:1[o2];[0:v][o2]overlay=x=(W-w)/2:y=(H-h)/2:shortest=1\" -y " + outputVideoPath;
                if (!string.IsNullOrWhiteSpace(fontsize))
                {
                    arguments = $@"-i " + inFile + " -filter_complex \"color=White:s=1200x700[v1];[v1]drawtext=fontfile=" + AppDomain.CurrentDomain.BaseDirectory + "SIMSUN.TTC:text='" + wm + "':x=" + 0 + ":y=" + 90 + ":fontsize=" + fontsize + ",drawtext=fontfile=" + AppDomain.CurrentDomain.BaseDirectory + "SIMSUN.TTC:text='" + wm + "':x=" + 150 + ":y=" + 360 + ":fontsize=" + fontsize + ",drawtext=fontfile=" + AppDomain.CurrentDomain.BaseDirectory + "SIMSUN.TTC:text='" + wm + "':x=" + 300 + ":y=" + 600 + ":fontsize=" + fontsize + "[o1];[o1]rotate=a=-PI*30/180:fillcolor=White@0[o1];[o1]colorkey=White:0.01:1[o2];[0:v][o2]overlay=x=(W-w)/2:y=(H-h)/2:shortest=1\" -y " + outputVideoPath;
                }
                else if (!string.IsNullOrWhiteSpace(fontsize)&& !string.IsNullOrWhiteSpace(transparency))
                {
                    //ffmpeg -i input.mp4 -vf "drawtext=text='Watermark Text':fontcolor=white:fontsize=24:x=100:y=100:alpha=0.5" -codec:a copy output.mp4
                    arguments = $@"-i " + inFile + " -filter_complex \"color=White:s=1200x700[v1];[v1]drawtext=fontfile=" + AppDomain.CurrentDomain.BaseDirectory + "SIMSUN.TTC:text='" + wm + "':x=" + 0 + ":y=" + 90 + ":fontsize=" + fontsize + ":alpha="+transparency+",drawtext=fontfile=" + AppDomain.CurrentDomain.BaseDirectory + "SIMSUN.TTC:text='" + wm + "':x=" + 150 + ":y=" + 360 + ":fontsize=" + fontsize + ":alpha="+transparency+",drawtext=fontfile=" + AppDomain.CurrentDomain.BaseDirectory + "SIMSUN.TTC:text='" + wm + "':x=" + 300 + ":y=" + 600 + ":fontsize=" + fontsize + ":alpha="+transparency+"[o1];[o1]rotate=a=-PI*30/180:fillcolor=White@0[o1];[o1]colorkey=White:0.01:1[o2];[0:v][o2]overlay=x=(W-w)/2:y=(H-h)/2:shortest=1\" -y " + outputVideoPath;
                }
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = "ffmpeg",
                    Arguments = arguments,
                    UseShellExecute = false,
                    RedirectStandardError = true,
                    RedirectStandardOutput = true
                };
                using (Process process = Process.Start(startInfo))
                {
                    process.WaitForExit(); // 等待FFmpeg进程执行完成
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("qskj视频添加水印" + e);
            }
        }
        #endregion
        #region 查询水印视频地址
        /// <summary>
        /// 查询水印视频地址
        /// </summary>
        /// <param name="key">文件标识</param>
        /// <param name="ft">文件格式</param>
        /// <param name="begintime">开始时间</param>
        /// <returns></returns>
        public static string GetUrl(string key, string ft, string begintime)
        {
            string url = string.Empty;
            try
            {
                string videoUrl = string.Empty, imageUrl = string.Empty;
                string dte = DateTime.Now.ToString("yyyyMMddHHmmss"), dts = DateTime.Now.AddMinutes(-30).ToString("yyyyMMddHHmmss");
                if (ft == "mp4")
                {
                    try
                    {
                        DataVideoUrl videoData = new DataVideoUrl();
                        videoUrl = GetFileDataUrl(key, dts, dte, begintime).Result;
                        videoData = JsonConvert.DeserializeObject<DataVideoUrl>(videoUrl);
                        if (!string.IsNullOrEmpty(videoData?.VideoSliceListObject?.VideoSlice[0]?.VideoSliceInfo?.StoragePath))
                        {
                            url = videoData?.VideoSliceListObject?.VideoSlice[0]?.VideoSliceInfo?.StoragePath;//视图库视频地址信息
                        }
                        return url;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "视频地址查询异常：" + e.Message);
                        return url;
                    }
                }
                else
                {
                    try
                    {
                        //DataImageUrl imageData = new DataImageUrl();
                        //imageUrl = GetImageFileDataUrl(key, dts, dte).Result;
                        //imageData = JsonConvert.DeserializeObject<DataImageUrl>(imageUrl);
                        //if (!string.IsNullOrEmpty(imageData?.ImageListObject?.Image[0]?.ImageInfo?.StoragePath))
                        //{
                        //    url = imageData?.ImageListObject?.Image[0]?.ImageInfo?.StoragePath;
                        //}
                        return url;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "图片地址查询异常：" + e.Message);
                        return url;
                    }

                }
            }
            catch (Exception e)
            {
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "证据地址查询异常：" + e.Message);
                return url;
            }
        }

        #endregion
    }
}
